﻿var interfacesManager = require('./interfacesManager');
var proxy = require('./Proxy');
var fs = require('fs');
var async = require('async');

var proxy_obj; //proxy
var debug_obj = false; //默认不输出调试信息
/**
 * apiProxy对象
 * @param {string} prefix 接口前缀
 */
var apiProxy = function (prefix){
    if (!proxy_obj) {
        throw new Error("请先调用init方法初始化接口参数");
    }
    this._prefix = (prefix || "")+".";
    this._queue = [];
}

/**
 * 生成一个api请求
 * @param {string} interfaceid 接口ID
 * @param {object} params 参数
 * @return {apiProxy} 
 */
apiProxy.prototype.Api = function (interfaceid, params) {
    interfaceid = this._prefix === '.' ? interfaceid : this._prefix + interfaceid;
    if (!proxy_obj._getInterface(interfaceid))
        return this;
    this._queue.push({
        params: params,
        interfaceid: interfaceid
    });
    return this;
}

/**
 * 执行请求
 * @param {function} callback
 * @return {apiProxy} 
 */
apiProxy.prototype.done = function (callback) {
    callback = typeof callback === 'function'?callback:function (data) {
        console.log(data);
    }
    var funs = [];
    var that = this;
    //设置错误回调函数
    that._errCallback = typeof that._errCallback === 'function' ? that._errCallback : function (err){
        console.log(err);
    }
    //生成请求函数
    if (that._queue.length > 0) {
        for (var i in that._queue) {
            funs.push(
                function (callback) {
                    (function (interfacesId, params) {
                        proxy_obj.request(interfacesId, params, function (data, newCookie) {
                            callback(null, {data:data,newCookie:newCookie});
                        }, that._errCallback, that._cookies, that._headers);
                    })(that._queue[i].interfaceid, that._queue[i].params)
                }
            );
        }
    }

    async.parallel(funs, function (err, data) {
        if (err) {
            that._errCallback(err);
            return;
        }
        callback.apply(that, data);
    });
    that._queue = [];
    return that;
}

/**
 * 错误处理
 * @param {function} errCallback 错误回调函数
 * @return {apiProxy}
 */
apiProxy.prototype.error = function (errCallback){
    this._errCallback = errCallback;
    return this;
}

/**
 * 设置cookie
 * @param {object} cookies
 * @return {apiProxy}
 */
apiProxy.prototype.cookies = function (cookies){
    this._cookies = cookies;
    return this;
}

/**
 * 设置header
 * @param {object} headers
 * @return {apiProxy}
 */
apiProxy.prototype.headers = function (headers){
    this._headers = headers;
    return this;
}

/**
 * 初始化接口信息
 * @param {string} path 接口配置文件地址
 * @param {string} encoding 配置文件编码
 * @return {apiProxy}
 */
apiProxy.init = function (path, encoding){
    intm = new interfacesManager(path, encoding, debug_obj);
    proxy_obj = new proxy(intm, debug_obj);
}

/**
 * 生成一个api请求
 * @param {string} interfaceid 接口ID
 * @param {object} params 参数
 * @param {string} prefix 接口前缀
 * @return {apiProxy}
 */
apiProxy.Api = function(interfaceid, params,prefix){
    var api = new apiProxy(prefix);
    return api.Api(interfaceid, params);
}

/**
 * 创建一个接口
 * @param {string} prefix 接口前缀
 * @return {apiProxy}
 */
apiProxy.Create = function (prefix){
    return new apiProxy(prefix);
}

/**
 * 直接代理请求
 * @param {httprequest} req
 * @param {httpresponse} res
 */
apiProxy.Proxy = function (req, res){
    if (!proxy_obj) {
        throw new Error("请先调用init方法初始化接口参数");
    }
    var interfaceId = req.url.split(/\?|\//)[1];
    proxy_obj.Proxy(interfaceId, req, res); //执行代理请求
}

/**
 * 代理请求,结果返回给callback函数
 * @param {string} interfaceId 接口名称
 * @param {httprequest} req
 * @param {httpresponse} res
 * @param {Function} callback 回调函数
 */
apiProxy.ProxyCallback = function (interfaceId,req, res, callback){
    if (!proxy_obj) {
        throw new Error("请先调用init方法初始化接口参数");
    }
    proxy_obj.Proxy(interfaceId, req, res,callback); //执行代理请求
}

/**
 * 是否调试
 * @param {bool} 是否调试
 */
apiProxy.Debug = function (debug){
    debug_obj = !!debug;
    if (proxy_obj) {
        proxy_obj.debug = debug;
        proxy_obj.Interfaces.debug = debug;
    }
}

module.exports = apiProxy;